package com.kjlink.internal.workreport.plan.service;

import cn.xuqiudong.common.base.service.BaseService;
import cn.xuqiudong.common.util.collections.CalcDiff4EntityRelationsUtil;
import com.kjlink.internal.workreport.plan.mapper.WorkPlanDetailMapper;
import com.kjlink.internal.workreport.plan.model.WorkPlanDetail;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 功能: :周工作计划详情 Service
 *
 * @author Vic.xu
 * @since 2024-10-10 09:56
 */
@Service
public class WorkPlanDetailService extends BaseService<WorkPlanDetailMapper, WorkPlanDetail> {

    @Override
    protected boolean hasAttachment() {
        return false;
    }


    public List<WorkPlanDetail> findByPlanId(Integer planId) {
        return mapper.findByPlanId(planId);
    }

    /**
     * 带入非完成的工作计划  !FINISHED
     *
     * @param planId 周工作计划ID
     */
    public List<WorkPlanDetail> bringInLastWeek(Integer planId) {
        //上周的结束时间为当前周的开始时间减一
        return mapper.bringInLastWeek(planId);
    }

    public void batchSave(Integer planId, List<WorkPlanDetail> list) {
        List<WorkPlanDetail> oldList = findByPlanId(planId);
        CalcDiff4EntityRelationsUtil.RelationResult<WorkPlanDetail> result = CalcDiff4EntityRelationsUtil.calc(oldList, list);
        // 1. 需要新增的计划
        result.getOnlyInNew().forEach(this::save);
        //2. 需要删除的计划
        List<WorkPlanDetail> onlyInOld = result.getOnlyInOld();
        if (!CollectionUtils.isEmpty(onlyInOld)) {
            int[] deleteIds = onlyInOld.stream().mapToInt(WorkPlanDetail::getId).toArray();
            this.delete(deleteIds);
        }
        //3. 需要更新的计划
        result.getUnion().forEach(this::save);

    }

    /**
     * 根据小组和周次查询详情
     */
    public List<WorkPlanDetail> findByGroupAndWeek(Integer groupId, String weekNumber) {
        return mapper.findByGroupAndWeek(groupId, weekNumber);
    }
}
